package cn.fscode.code.generator.repository;

import cn.fscode.code.generator.mapper.GenTableMapper;
import cn.fscode.code.generator.model.po.GenTablePO;
import cn.fscode.code.generator.model.req.GenTablePageReq;
import cn.fscode.commons.core.page.PageDomain;
import cn.fscode.commons.core.page.TableSupport;
import cn.fscode.commons.tool.core.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Repository
public class GenTableRepository extends ServiceImpl<GenTableMapper, GenTablePO> implements IService<GenTablePO> {
    @Resource
    private GenTableMapper genTableMapper;

    public void saveOrUpdateGenTable(GenTablePO req) {
        String tableName = req.getTableName();
        LambdaQueryWrapper<GenTablePO> wrapper = Wrappers.<GenTablePO>lambdaQuery()
                .eq(GenTablePO::getTableName, tableName).eq(GenTablePO::getDatasourceId, req.getDatasourceId());
        GenTablePO genTable = genTableMapper.selectOne(wrapper);
        if (Objects.nonNull(genTable)) {
            req.setId(genTable.getId());
            genTableMapper.updateById(req);
        } else {
            genTableMapper.insert(req);
        }
    }

    public IPage<GenTablePO> pageGenTable(GenTablePageReq req) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        LambdaQueryWrapper<GenTablePO> wrapper = Wrappers.<GenTablePO>lambdaQuery()
                .like(StringUtils.isNotEmpty(req.getTableName()), GenTablePO::getTableName, req.getTableName())
                .like(StringUtils.isNotEmpty(req.getTableComment()), GenTablePO::getTableComment, req.getTableComment())
                .eq(Objects.nonNull(req.getDatasourceId()), GenTablePO::getDatasourceId, req.getDatasourceId())
                .orderByDesc(GenTablePO::getUpdateTime);
        return this.page(new Page<>(pageNum, pageSize), wrapper);
    }

    public List<GenTablePO> listByDatasourceId(Long datasourceId) {
        LambdaQueryWrapper<GenTablePO> wrapper = Wrappers.<GenTablePO>lambdaQuery()
                .eq(GenTablePO::getDatasourceId, datasourceId);
        return this.list(wrapper);
    }
}
